import { Component, OnInit, ViewChild } from '@angular/core';
import { DatePipe } from '@angular/common';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Router, ActivatedRoute, NavigationExtras} from '@angular/router';
import { SellAddService } from '../sell-ad/sell-ad.service'
import { NzDatePickerComponent } from 'ng-zorro-antd/date-picker';
import { CommonService } from 'src/app/services-common/common.service';

@Component({
  selector: 'app-sell-ad-save',
  templateUrl: './sell-ad-save.component.html',
  styleUrls: ['./sell-ad-save.component.scss'],
  providers: [DatePipe]
})
export class SellAdSaveComponent implements OnInit {
  @ViewChild('endDatePicker') endDatePicker!: NzDatePickerComponent;

  // 路由传参
  routeForms: any ={
    mode: 0 // 0：新增,1：编辑,2：查看,3：复制
  };
  // formDatas
  formDatas: any = {
    // state: '', // 状态 0启用 1禁用
    userType: '', // 适用用户
    title: '', // 标题
    beginTime: '', // 开始时间
    endTime: '', // 结束时间
    remark: '', // 备注
    type: '1', // 类型 1.链接 2.商品 3.搜索词 4.第三级分类
    url: '', // 跳转配置:类型为链接为链接,商品为商品id,搜索词为搜索词.分类为分类id
    params: '', // 参数
    imgUrl: '', // 图片url
    textColor: '0', // 文字颜色 0：深色 1：浅色
    backColor: '' // 背景颜色
  }
  // 时间arrs
  effectiveTime: any = [];
  // 适用用户 b端=门店商户，c端=个人用户
  checkOptions: any = [
    { label: 'B端', value: '2' },
    { label: 'C端', value: '1' }
  ]
  // 上传loading
  uploadLoading: boolean = false;
  // 跳转方式 1.商品id 2.链接 3.搜索词 4.分类（2021/7/28）
  typeSet: any = { 1: '商品id', 2: '链接', 3: '搜索词', 4: '分类' };
  // subLoading
  subLoading: boolean = false;

  // 映射Options
  mappingOptions: any = [];

  constructor(
    private router: Router,
    private datePipe: DatePipe,
    private activatedRoute: ActivatedRoute,
    private message: NzMessageService,
    private service: SellAddService,
    private commonService: CommonService
  ) {
    activatedRoute.queryParams.subscribe((res: any) => {
      this.routeForms = res || {};
    })
  }

  ngOnInit() {
    this.getMappingData()
    if (this.routeForms.mode != 0) {
      this.loadDetailData()
    }
  }

  // 获取
  async getMappingData() {
    let params = {
      page: 1,
      pageSize: 10000
    }
    const res: any = await this.commonService.getMappingData(params);
    if (res.code === 0) {
      const { records } = res.data || {};
      this.mappingOptions = records || []
    }
  }

  // 查询详情
  loadDetailData() {
    this.service.queryAdvertisementDetail({ id: this.routeForms.id }).subscribe((res: any) => {
      const { data } = res

      if (data) {
        for (let key in this.formDatas) {
          // 开始结束时间赋值
          if (this.formDatas[key] == 'beginTime' || this.formDatas[key] == 'endTime') {
            this.formDatas['beginTime'] = data['beginTime'] ? new Date(data.beginTime) : data['beginTime'];
            this.formDatas['endTime'] = data['endTime'] ? new Date(data.endTime) : data['endTime'];
          }
          this.formDatas[key] = data[key] ? String(data[key]) : data[key]
        }
        
        if (data.userType) {
          this.checkOptions.forEach((ele: any) => {
            if (data.userType == '0') {
              ele.checked = true;
            } else {
              if (String(data.userType).indexOf(ele.value) != -1) {
                ele.checked = true;
              }
            }
          });
        }
      }
    })
  }

  /**
   * 保存编辑
   * @returns 
   * routeForms.mode 0：新增,1：编辑,2：查看,3：复制
   */
  preserData() {
    if (!this.verifData()) {
      return
    }
    let params = {
      ...this.formDatas,
      beginTime: this.formDatas.beginTime ? this.datePipe.transform(this.formDatas.beginTime, 'yyyy-MM-dd HH:mm:ss') : '',
      endTime: this.formDatas.endTime ? this.datePipe.transform(this.formDatas.endTime, 'yyyy-MM-dd HH:mm:ss') : ''
    }
    if (this.routeForms.mode == 1) {
      params.id = this.routeForms.id
    }
    // console.log('timetime', params)
    // return
    this.subLoading = true;

    if (this.routeForms.mode == 0 || this.routeForms.mode == 3) {
      this.service.addAdvertisementData(params).subscribe((res: any) => {
        this.subLoading = false;
  
        if (res.code == 0) {
          this.message.success('添加成功');
          this.router.navigate(['/sell/ad']);
        } else {
          this.message.error(res.message || '添加失败');
        }
      }, (error: any) => {
        this.subLoading = false;
        this.message.error(error);
      })
    } else if (this.routeForms.mode == 1) {
      this.service.editDeleteData(params).subscribe((res: any) => {
        this.subLoading = false;
  
        if (res.code == 0) {
          this.message.success('添加成功');
          this.router.navigate(['/sell/ad']);
        } else {
          this.message.error(res.message || '添加失败');
        }
      }, (error: any) => {
        this.subLoading = false;
        this.message.error(error);
      })
    }
  }

  // checkbox
  changeCheckbox(value: object[]): void {
    let tempArr: any[] = value.map((item: any) => {
      if (item.checked) {
        return item.value
      }
    }).filter(tag => tag);

    if (tempArr.length == 2) {
      this.formDatas.userType = '0';
    } else {
      this.formDatas.userType = tempArr.join(',');
    }
  }

  // ********************************** 时间选择处理 START **********************************
  disabledStartDate = (startValue: Date): boolean => {
    if (!startValue || !this.formDatas.endTime) {
      return false;
    }
    return startValue.getTime() > new Date(this.formDatas.endTime).getTime();
  };

  disabledEndDate = (endValue: Date): boolean => {
    if (!endValue || !this.formDatas.beginTime) {
      return false;
    }
    return endValue.getTime() <= new Date(this.formDatas.beginTime).getTime();
  };
  // ********************************** 时间选择处理 END **********************************

  // 输入链接
  oninputLink(ev: any) {
    const { type } = this.formDatas;
    if (type == 1) {
      this.formDatas.url = ev.target.value.replace(/[^\d]/g, '');
    }
  }

  // 图片上传
  onModalPreview(ev: any) {
    const { originFileObj }: any = ev?.file
    this.uploadInterface(originFileObj)
  }
  // uploadInterface
  async uploadInterface(file: any) {
    if (!file || this.uploadLoading) {
      return
    }

    try {
      this.uploadLoading = true;
      const res: any = await this.service.uploadFileData(file)
      this.uploadLoading = false;

      if (res.code == 0) {
        this.message.success('图片上传成功');
        this.formDatas.imgUrl = res.data;
      } else {
        this.message.error(res.message);
      }
    } catch (error: any) {
      this.uploadLoading = false;
      this.formDatas.imgUrl = '';
      this.message.error(error);
    }
  }

  // 验证
  verifData() {
    if (!this.formDatas.userType) {
      this.message.warning('请选择适用用户');
      return false
    } else if (!this.formDatas.title) {
      this.message.warning('请输入标题');
      return false
    } else if (!this.formDatas.imgUrl) {
      this.message.warning('请选择图片');
      return false
    } else if (this.commonService.isEmpty(this.formDatas.textColor)) {
      this.message.warning('请选择文字颜色');
      return false
    } else if (this.commonService.isEmpty(this.formDatas.backColor)) {
      this.message.warning('请输入背景颜色');
      return false
    } else {
      return true
    }
  }

  // 映射链接备注Filter
  remarkFilter(key: any) {
    let tempObj: any = this.mappingOptions.find((item: any) => {
      return item?.key === key
    })
    return tempObj?.remarks || '';
  }
}
